<?php
namespace app\api\controller;
use think\App;
use app\api\common\controller\Api;
use app\common\library\EasyWechat;
use think\cache\driver\Redis;
use EasyWeChat\Factory;
use think\facade\Request;
use think\facade\Db;
use think\facade\Config;
use think\facade\Cache;
// use app\api\common\controller\AfterPay;
// use app\api\common\controller\RechargeGift;
// use app\api\model\Customer;
// use app\api\model\send\MemberDraw;
// use app\api\model\send\MemberProduct;
// use app\api\common\controller\MidOrder;
// use app\common\model\PackageCard as packageCardModel;
// use app\api\common\controller\InsCoupon;
// use app\common\model\MembershipInterests;
// use app\api\model\Order as orderModel;
// use app\api\common\controller\ReceiveCoupon;
// use app\api\common\controller\BalancePayment;
// use app\common\model\WalletLog;
// use app\common\model\Summary;
class Wx extends Api{
  private $order = null;
  private $midOrder = null;
  private $coupon_id = 0;
  private $share_member_id = 0;
  private $current_member_id = 0;
  private $newOrOldMember = 0;//0-新用户1-老用户
  private $msg = "登录成功";
  protected function _structure(){
   
    $parameters = $this->request::param();
    if(isset($parameters['coupon_id']) && $parameters['coupon_id'] > 0){
      $this->coupon_id = $parameters['coupon_id'];
    }
    if(isset($parameters['share_member_id']) && $parameters['share_member_id'] > 0){
      $this->share_member_id = $parameters['share_member_id'];      
    }
    //$this->MidOrder = new MidOrder;
  }
  public function testPay(){
      $data = $this->prepareOnlinePay('45345',0.01,1);
      return json($data);
  }
  public function refund(){
      //$message['out_trade_no'] = 12022071520;
      //$order = Db::name('wechat_payment') -> where('flow_id',$message['out_trade_no']) -> findOrEmpty();
      
      //if (!$order || $order['paid_at']) { // 如果订单不存在 或者 订单已经支付过了
          //return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
      //}
	    
          //$this->order = $order;
          //修改订单状态
          //$update['paid_at'] = date('Y-m-d H:i:s');
          //$update['status'] = 1;
          //Db::name('wechat_payment')->where(['flow_id'=>$message['out_trade_no']])->update($update);
          //halt($order);
          //halt($order['orders_id']);
          //Db::name('order') -> where('id',$order['orders_id']) -> update(['orders_status' => 1,'code' => $this->getcode()]);
          
        
     
      //halt(1);
      // 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
        //$app->refund->byOutTradeNumber(string $number, string $refundNumber, int $totalFee, int $refundFee, array $config = []);
    
        // Example:
        
        $result = $this->payApp->refund->byOutTradeNumber('43534retertre45', 'eref5346fgfdg', 0.01, 0.01, [
        // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '退费测试',
        ]);
  }
  public function notify(){
    $response = $this->payApp->handlePaidNotify(function ($message, $fail) {
        // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
        Db::name('log') -> insertGetId(['info'=>1]);
        Db::name('log') -> insertGetId(['info'=>json_encode($message)]);
        $order = Db::name('wechat_payment') -> where('flow_id',$message['out_trade_no']) -> findOrEmpty();
        if (!$order || $order['paid_at']) { // 如果订单不存在 或者 订单已经支付过了
          return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
        }
	    if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
        // 用户是否支付成功
        if ($message['result_code'] === 'SUCCESS') {
          $this->order = $order;
          //修改订单状态
          $update['paid_at'] = date('Y-m-d H:i:s');
          $update['status'] = 1;
          Db::name('wechat_payment')->where(['flow_id'=>$message['out_trade_no']])->update($update);
          Db::name('order') -> where('id',$order['orders_id']) -> update(['orders_status' => 1,'code' => $this->getcode()]);
          
        } elseif ($message['result_code'] === 'FAIL') {// 用户支付失败
          // 用户支付失败,不做任何处理
        }
      } else {
        //通讯失败，暂不不做任何处理
        
      }
      return true; // 返回处理完成
    });
  }

  //核销码
  public function getcode($len=6,$format='ALL'){    
    switch($format) {
        case 'ALL':
        $chars='ABCDEFGHIJKMNOPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz123456789-@#~'; break;
        case 'CHAR':
        $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break;
        case 'NUMBER':
        $chars='0123456789'; break;
        default :
        $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
        break;
    }
    mt_srand((double)microtime()*1000000*getmypid());
    $code="";
    while(strlen($code)<$len)
    $code.=substr($chars,(mt_rand()%strlen($chars)),1);
    return $code;
  }

  public function login(){
	  
    if(count($this->memberLoginData)>0){
      $this->current_member_id = $this->user_member_id;
         $this->result($this->msg, $this->memberLoginData,200,'json');
     
    }

    $code=Request::param('code','post');

    $this->wxApp = Factory::miniProgram($this->wx_config);
    $loginInfo = $this->wxApp->auth->session($code);
    if($loginInfo){
      $result = [
        "status" => 200,
        "message" => "成功",
        "data" => $loginInfo
      ];
      return json($result);
    }else{

    }
  }

	//授权昵称等基础信息
  public function getBaseInfo(){
    $iv = Request::param('iv','post');
    $encryptedData = Request::param('encryptedData','post');
    $session = Request::param('result','post');

    $time = time();
    $decryptedData = $this->wxApp->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
    $addressInfo = getAddressByIp(request()->ip());
    $country = "";
    $region = "";
    $area = "";
    $city = "";
    if($addressInfo['code'] == 200){
      $country = $addressInfo['data']['country'];
      $region = $addressInfo['data']['region'];
      $area = $addressInfo['data']['area'];
      $city = $addressInfo['data']['city'];
    }
    $data = [
      "members_nickname" => base64_encode($decryptedData['nickName']),
      "members_openid" => $session['openid'],
      "members_unionid" =>'',// $session['unionid']
      "members_mobile" => 0,
      "members_avatar" => $decryptedData['avatarUrl'],
      "members_prevtime" => 0,
      "members_logintime" => $time,
      "members_loginip" => request()->ip(),
      "members_createtime" => $time,
      "parent_members_id" => 0,
      "city" => $city,
      "country" => $country,
      "area" => $area,
      "region" => $region
    ];
    $loginUser = Db::name('members') -> where('members_openid',$session['openid']) -> findOrEmpty();
   	if($loginUser){//登录注册
   		$member_id = $loginUser['members_id'];
      unset($data["members_openid"]);
      unset($data["members_unionid"]);
      unset($data["members_mobile"]);
      unset($data["members_createtime"]);
      unset($data["parent_members_id"]);
      unset($data["invite_code"]);
      $data['members_id'] = $loginUser['members_id'];
      $data['members_prevtime'] = $loginUser['members_logintime'];
      Db::name('members') -> update($data);
      $this->newOrOldMember = 1;

   	}else{//首次登录

       $data["invite_code"] = getUserInviteCode();
       $member_id = Db::name('members') -> strict(false) -> insertGetId($data);
       $loginUser = Db::name('members') -> where('members_id',$member_id) -> findOrEmpty();
    }  
    $redis = Cache::store('redis');
    $key = Config::get('token.key');
    $str = Config::get('token.str').'||'.$member_id;
    $token = authcode($str,'ENCODE',$key,0); //加密
    $user_id = Config::get('token.memberprefix')."-".$member_id;
    $expire = Config::get('token.expire');
    $redis->set($user_id,$token,$expire);
    $this->current_member_id = $member_id;
    $this->msg = "OK";
    $loginUser['members_nickname'] = base64_decode($loginUser['members_nickname']);
    $data = [
      "accessToken" => $token,
      "tokenExpired" => $expire,
      "user" => $loginUser
    ];
 
    $this->result($this->msg, $data,200,'json');
  }



  //授权手机号
  public function getMobile(){
    $iv = Request::param('iv','post');
    $encryptedData = Request::param('encryptedData','post');
    $code = Request::param('code','post');

    $this->wxApp = Factory::miniProgram($this->wx_config);
    $session = $this->wxApp->auth->session($code);
    $decryptedData = $this->wxApp->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
    $flag = Db::name('members') -> where('members_openid',$session['openid']) -> update(['members_mobile' => $decryptedData['phoneNumber']]);
    $this->msg = "授权成功";
 
    if(count($this->memberLoginData)>0){
        $this->memberLoginData['user']['members_mobile'] = $decryptedData['phoneNumber'];
       $this->result($this->msg, $this->memberLoginData,200,'json');
    }
  
  }
  
}
